<?php

namespace Core\Utils;

class Utils
{
    /**
     * curl请求
     * @return string
     */
    public static function sendCurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 3);
        curl_setopt( $ch, CURLOPT_TIMEOUT , 8);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if ($params) {
            if (is_array($params)) {
                $paramsString = http_build_query($params);
            } else {
                $paramsString = $params;
            }
        } else {
            $paramsString = "";
        }
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $paramsString);
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($paramsString ){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$paramsString);
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
    /**
     * 银行卡三元素认证
     * */
    public static function ThreeElementAuthentication($bankAccount,$real_name,$idcard){
        $host = "https://ckid.market.alicloudapi.com";
        $path = "/lundear/verifyBankThree";
        $method = "GET";
        $appcode = "dd537d999de9483493c0d4097f9ebd8e";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "cardno=".$bankAccount."&name=".urlencode($real_name)."&idcard=".$idcard;
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $response = curl_exec($curl);
        curl_close( $curl );
        return $response;
    }
    /**
     * 订单号生成
     * */
    public static function createOrderNo(){
        return date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }
    /**
     * 判断长度6-18位
     * */
    public static function islength6_18($str){
        if(strlen($str) > 18 || strlen($str)<6){
            return false;
        }
        return true;
    }
    /**TODO 判断账号格式
     *
     * */
    public static function usernameChecking($phone){
        if(strlen($phone) > 18 || strlen($phone)<6){
            return false;
        }
        return true;
    }
    /**TODO 判断账号格式
     *
     * */
    public static function phoneChecking($phone){
        $regex = '/^1[0-9]{10,10}$/';//最强手机验证正则
        if (preg_match($regex, $phone) == 0) {
            return false;
        }
        return true;
    }
    /**
     * 格式化时间戳
     * @param $time
     * @return false|string
     */
    public static function dateTime($time = ''){
        $time = $time ?? time();
        return date('Y-m-d H:i:s', $time);
    }
    /**TODO 判断邮箱验证
     *
     * */
    public static function emailChecking($email){
        if (preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email)) {
            return true;
        } else {
            return false;
        }
    }
    public static function yc_phone($phone){
       return substr_replace($phone,'****',3,4);
    }
    public static function yc_truename($userName){
        $strlen = mb_strlen($userName, 'utf-8');
        $firstStr = mb_substr($userName, 0, 1, 'utf-8');
        $lastStr = mb_substr($userName, -1, 1, 'utf-8');
        $resultName = ($strlen == 2) ? $firstStr . str_repeat('*', mb_strlen($userName, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
        return $resultName;
    }
    public static function yc_idCard($str){
        return substr_replace($str,str_repeat("*",6),6,6);
    }
    /**
     * 生成数字和字母
     *
     * @param int $len 长度
     * @return string
     */
    public static function alnum($len = 6)
    {
        return self::build('alnum', $len);
    }

    /**
     * 仅生成字符
     *
     * @param int $len 长度
     * @return string
     */
    public static function alpha($len = 6)
    {
        return self::build('alpha', $len);
    }

    /**
     * 生成指定长度的随机数字
     *
     * @param int $len 长度
     * @return string
     */
    public static function numeric($len = 4)
    {
        return self::build('numeric', $len);
    }

    /**
     * 生成指定长度的无0随机数字
     *
     * @param int $len 长度
     * @return string
     */
    public static function nozero($len = 4)
    {
        return self::build('nozero', $len);
    }

    /**
     * 能用的随机数生成
     * @param string $type 类型 alpha/alnum/numeric/nozero/unique/md5/encrypt/sha1
     * @param int    $len  长度
     * @return string
     */
    public static function build($type = 'alnum', $len = 8)
    {
        switch ($type) {
            case 'alpha':
            case 'alnum':
            case 'numeric':
            case 'nozero':
                switch ($type) {
                    case 'alpha':
                        $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'alnum':
                        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'numeric':
                        $pool = '0123456789';
                        break;
                    case 'nozero':
                        $pool = '123456789';
                        break;
                }
                return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len);
            case 'unique':
            case 'md5':
                return md5(uniqid(mt_rand()));
            case 'encrypt':
            case 'sha1':
                return sha1(uniqid(mt_rand(), true));
        }
    }

    /**
     * 根据数组元素的概率获得键名
     *
     * @param array $ps     array('p1'=>20, 'p2'=>30, 'p3'=>50);
     * @param int   $num    默认为1,即随机出来的数量
     * @param bool  $unique 默认为true,即当num>1时,随机出的数量是否唯一
     * @return mixed 当num为1时返回键名,反之返回一维数组
     */
    public static function lottery($ps, $num = 1, $unique = true)
    {
        if (!$ps) {
            return $num == 1 ? '' : [];
        }
        if ($num >= count($ps) && $unique) {
            $res = array_keys($ps);
            return $num == 1 ? $res[0] : $res;
        }
        $max_exp = 0;
        $res = [];
        foreach ($ps as $key => $value) {
            $value = substr($value, 0, stripos($value, ".") + 6);
            $exp = strlen(strchr($value, '.')) - 1;
            if ($exp > $max_exp) {
                $max_exp = $exp;
            }
        }
        $pow_exp = pow(10, $max_exp);
        if ($pow_exp > 1) {
            reset($ps);
            foreach ($ps as $key => $value) {
                $ps[$key] = $value * $pow_exp;
            }
        }
        $pro_sum = array_sum($ps);
        if ($pro_sum < 1) {
            return $num == 1 ? '' : [];
        }
        for ($i = 0; $i < $num; $i++) {
            $rand_num = mt_rand(1, $pro_sum);
            reset($ps);
            foreach ($ps as $key => $value) {
                if ($rand_num <= $value) {
                    break;
                } else {
                    $rand_num -= $value;
                }
            }
            if ($num == 1) {
                $res = $key;
                break;
            } else {
                $res[$i] = $key;
            }
            if ($unique) {
                $pro_sum -= $value;
                unset($ps[$key]);
            }
        }
        return $res;
    }
    /**
     * 16进制
     * @return string
     */
    public static function setUuid($phone){
        $club_code = $phone-10000000000;
        return dechex($club_code);
    }
    /**
     * 获取全球唯一标识
     * @return string
     */
    public static function uuid()
    {
        return sprintf(
            '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
    public static function writeLog($content){
        file_put_contents("log.txt",$content."\r\n",FILE_APPEND);
    }
    public static function writePayLog($content){
        file_put_contents("pay.txt",$content."\r\n",FILE_APPEND);
    }
    public static function writeSettLog($content){
        file_put_contents("sett.txt",$content."\r\n",FILE_APPEND);
    }
}